import React from 'react';
import { Button,Alert,Select,Checkbox,Table, Form, Radio, Input, Row, Col, message, Icon, Upload  } from 'antd';
import $ from 'jquery';
import _ from 'lodash';
import classNames from 'classnames';
const RadioGroup = Radio.Group,
  RadioButton = Radio.Button,
  CheckboxGroup = Checkbox.Group,
  Option = Select.Option,
  createForm = Form.create,
  FormItem = Form.Item;
import {
  API_URL,
  SPECIAL_UPLOAD,
  SPECIALIST,
  fetchPortrait,
  PORTRAIT,
  register,
  _validate,
  formItemLayout,
  sendSms,
  checkExists,
  checkSms,
  updateSpecialist,
  availabel,
  fetchDatum,
  login,
  getUser,
  special_operate,
  fetchAttachById,
  portrait,
  uploadChangeHandle,
  portraitSet,
  fetchAttachByEntry
} from '../store/actions';
require('../../css/form-register.css');

function noop() {
    return false;
}
let s;
function checkForm(a,b,rules,rule, value, callback){
    const _r = eval(rules[a][b]['expr']),
        msg = rules[a][b]['rule'],
        result = _r.test(value);
    if (!result && value) {
        callback(msg)
    }else{
        callback();
    }
}
const tempHospitalData = [
      {
          name:'医院名称0',
          id:'hospital0',
          area:[]
      },{
          name:'医院名称1',
          id:'hospital1',
          area:[]
      }
  ],
  tempServiceData = [
      {
          id:'time0',
          label:'9:00-12:00'
      },{
          id:'time1',
          label:'14:00-17:00'
      },{
          id:'time2',
          label:'19:00-21:00'
      }
  ];
class _CheckMobBySms extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            sendTxt:'发送短信验证码',
            sendStyle:'primary',
            sendable:false,
            timer:null,
            rules: null
        }
    }
    sendSms(e){
        const _this = this;
        _validate(e,_this,function(data){
            let i = 120;
            _this.props.dispatch(sendSms(data.mobile,function(){
                message.success('正在请求发送验证码短信',2);
                _this.props.afterSend(data.mobile);
                s = setInterval(function(){
                    if(i>0){
                        _this.setState({
                            sendStyle:'',
                            sendable:true,
                            sendTxt:`${i--} 秒后可以重发`
                        });
                    }else{
                        _this.setState({
                            sendTxt:`发送短信验证码`,
                            sendStyle:'primary',
                            sendable:false,
                            timer:null
                        },function(){
                            s = clearInterval(s)
                        });
                    }
                },1000);
            },function(){
                message.warning('业务处理失败',1)
            },function(e){
                message.error('error请求失败',1)
            }));
        })
    }
    checkMob(rule, value, callback){
        checkForm('common','mobile', this.state.rules, rule, value, callback)
    }
    mobExists(rule, value, callback){
        const _this = this;
        if(_this.props._target){
            this.props.dispatch(checkExists('mobile',rule,value,callback,_this.props._target.mobile))
        }else{
            this.props.dispatch(checkExists('mobile',rule,value,callback))
        }
    }
    componentWillMount(){}
    componentWillReceiveProps(nextProp){
        if(!this.state.rule){
            this.setState({
                rules:nextProp.rules
            })
        }
    }
    componentWillUnmount(){
        s = clearInterval(s)
    }
    render(){
        const { getFieldProps } = this.props.form;
        const mobileProps = getFieldProps('mobile', {
            validate: [
                {
                    rules: [
                        { validator: this.mobExists.bind(this)}
                    ],
                    trigger: 'onChange'
                },
                {
                    rules: [
                        { required: true, message: '请输入手机号' },
                        { validator: this.checkMob.bind(this)}
                    ],
                    trigger: 'onChange'
                }
            ]
        });
        const sendBtn = (
          <a
            disabled={this.state.sendable}
            type={this.state.sendStyle}
            onClick={this.sendSms.bind(this)}>
              {this.state.sendTxt}
          </a>
        );
        return (
          <div>
              <Form horizontal form={this.props.form} >
                  <FormItem
                    {...formItemLayout}
                    label="手机号"
                  >
                      <Input
                        disabled={this.state.sendable}
                        {...mobileProps}
                        placeholder="请输入手机号"
                        addonAfter={sendBtn}
                      />

                  </FormItem>
              </Form>
          </div>
        )
    }
}

const CheckMobBySms = createForm()(_CheckMobBySms);

class _SubmitCode extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            active:false,
            pwType:'password',
            eyeStyle:'eye'
        }
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        if(!_this.props.mobile){
            message.error('请输入手机号');
            return;
        }
        _validate(e,_this,function(code){
            const opts = {
                mobile:_this.props.mobile,
                smscode:code.code
            };
            _this.props.dispatch(checkSms(opts,function(){
                const userInfo = {
                    username:opts.mobile,
                    password:code.password
                };
                _this.props.dispatch(special_operate('register',{},userInfo,function(res){
                    message.success(`注册成功，请尽快完善个人信息！`,2);
                    _this.props.dispatch(login(userInfo,function(){
                        _this.props.goStep(1);
                    },function(res){
                        message.warning(`初始化信息失败，请重新登录！${res.head.msg}`,2);
                    },function(){
                        message.error(`初始化信息失败，请重新登录！${res.head.msg}`,2);
                    }))
                },function(res){
                    if(res.head.msg == '002'){
                        message.error(`用户名${opts.mobile}已经被注册过了`,2);
                    }
                }));
            },function(res){
                message.error(res.head.msg);
               _this.props.form.resetFields();
            },function(){
                message.error('请求出错了.....',1);
            }))
        });
    }
    handleBack(e){
        e.preventDefault();
        this.context.router.push('/login')
    }
    showPassword(){
        if(this.state.pwType=='text'){
            this.setState({
                pwType: 'password',
                eyeStyle:'eye'
            })
        }else{
            this.setState({
                pwType: 'text',
                eyeStyle:'eye-o'
            })
        }
    }
    render(){
        const { getFieldProps } = this.props.form,
        codeProps = getFieldProps('code', {
            validate: [{
                rules: [
                    { required: true,message: '请输入短信验证码' }
                ],
                trigger: 'onBlur'
            }]
        }),
          pwProps = getFieldProps('password', {
              validate: [{
                  rules: [
                      { required: true, message: '请设置密码' }
                  ],
                  trigger: 'onBlur'
              }],
          }),
          showPW = (
            <Icon
              style={{
                padding:'4px 7px'
              }}
              type={this.state.eyeStyle}
              onClick={this.showPassword.bind(this)}
            />
          );

        return (
          <div>
              <Form horizontal form={this.props.form} >
                  <FormItem
                    {...formItemLayout}
                    label="短信验证码"
                  >
                      <Input {...codeProps} />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="设置密码"
                    help="可以点击右侧的眼睛图标来查看已经输入的密码"
                  >
                      <Input
                        type={this.state.pwType}
                        {...pwProps}
                        addonAfter={showPW}
                      />
                  </FormItem>
                  <FormItem  wrapperCol={formItemLayout.noLabel}>
                      <Button type="primary" disabled={this.state.active} onClick={this.handleSubmit.bind(this)}>下一步</Button>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      <Button type="ghost" onClick={this.handleBack.bind(this)}>返回登录</Button>
                  </FormItem>
              </Form>
          </div>
        )
    }
}
const SubmitCode = createForm()(_SubmitCode);
class _FillInfo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: {},
            specialist: this.props._target,
            portrait: this.props.portrait,
            fileList: {},
            attachment:this.props.attachment,
            user: this.props.user,
            rules: this.props.rules
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
    }
    resetFields(){
        this.props.form.resetFields()
    }
    static contextTypes = {
        router:React.PropTypes.object
    };
    componentWillMount(){
        const _this = this;
        _this.props.dispatch(fetchDatum([
            {
                name:'department',
                enabled: true
            },{
                name:'title',
                enabled: true
            },{
                name:'gender',
                enabled: true
            },{
                name:'modality',
                enabled: true
            }
        ],function(datas){
            _this.setState({
                data:datas
            },function(){
                const {setFieldsValue} = _this.props.form;
                if(_this.props._target){
                    const initData = Object.assign({},_this.props._target);
                    if(initData.workingtime == '[]'){
                    }else{
                        //有数据
                        const _wt = initData.workingtime;
                        _wt.forEach(_w => {
                            initData[_w.label] = _w.weekday
                        });
                        delete initData.workingtime
                    }
                    setFieldsValue(initData);
                }else{
                    _this.resetFields()
                }
            })
        }));
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            user: nextProp.user,
            attachment:nextProp.attachment,
            rules:nextProp.rules
        })
    }
    checkUserName(rule, value, callback){
        checkForm('account','username', this.state.rules, rule, value, callback)
    }
    userExists(rule, value, callback){
        const _this = this;
        if(_this.props._target){
            this.props.dispatch(checkExists('username',rule,value,callback,_this.props._target.username))
        }else{
            this.props.dispatch(checkExists('username',rule,value,callback))
        }
    }
    checkName(rule, value, callback){
        checkForm('account','name',this.state.rules, rule, value, callback)
    }
    checkMob(rule, value, callback){
        checkForm('common','mobile',this.state.rules, rule, value, callback)
    }
    mobExists(rule, value, callback){
        const _this = this;
        if(_this.props._target){
            this.props.dispatch(checkExists('mobile',rule,value,callback,_this.props._target.mobile))
        }else{
            this.props.dispatch(checkExists('mobile',rule,value,callback))
        }
    }
    checkIdcard(rule, value, callback){
        checkForm('common','idcard',this.state.rules,rule, value, callback)
    }
    normFile(e){
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    uploadChangeHandler(cate,info){
        const _this = this;
        return uploadChangeHandle(cate,info,_this)
    }
    portraitHandler(info){
        const _this = this;
        return portraitSet(info,_this)
    }

    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        _validate(e,_this,function(data){
            let account_id = {account_id:_this.state.user.user.account_id};
            delete data.files;
            let _data = Object.assign({},account_id,data);
            let workingtime = [];
            for(let e in data){
                const _reg = /^time\d+/;
                if(_reg.test(e)){
                    const _wt = {
                        label: e,
                        weekday:data[e]
                    };
                    workingtime.push(_wt);
                    delete _data[e];
                }
            }

            const attachment = [],
              willUploadFiles = _this.state.fileList;
            _.forIn(willUploadFiles,(v,k)=>{
                if(v.length> 0 ){
                    attachment.push({[k]:v})
                }
            })
            _data.workingtime = workingtime;
            _data.attachment = attachment;
            _data.specialist_id = _this.state.user.user.specialist_id;
            _data.ispass = 0;
            _data.specialstatus = 1;
            _this.props.dispatch(special_operate('update','',_data,function(res){
                message.success('成功提交个人资料',1);
                //_this.props.dispatch(fetchAttachById(_this.state.portrait.id,0))
                _this.props.dispatch(special_operate('detail',account_id,{},function(res){
                    const _json = {content:{accessToken:_this.props.user.accessToken,user:res.content}};
                    try{_this.props.dispatch(getUser(_json))}catch (e){}
                    _this.props.goStep(2)
                }));
            },function(res){
                message.error(res.head.msg,1)
            }));
        })
    }
    fileTypeLimit(types,file){
        const fileType = file.type,
          typeStr = types.join('、');
        let isOk = false;
        for(let i = 0;i<types.length;i++){
            try{
                isOk = new RegExp(types[i]).test(fileType);
                if(isOk){
                    break;
                }
            }catch(e){consloe.log(e)}
        }
        if(!isOk){
            message.error(`您上传文件的格式只能是：${typeStr}格式`)
            return isOk
        }

    }
    render() {
        let curPortrait = null;
        if(this.state.fileList && this.state.fileList.portrait){
            curPortrait = {};
            const _id = this.state.fileList.portrait;
            curPortrait.id = _id;
            curPortrait.url = `${API_URL}attachment/${_id}?accessToken=${this.state.user.accessToken}`
        }else{
            curPortrait = this.state.portrait
        }
        const _modalities = this.state.data.modality && _.map(this.state.data.modality,(_m) => {
                return {
                    label:_m.code,
                    value:_m.id
                }
            }),
          _departments = this.state.data.department && this.state.data.department.map(_h => {
                return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
            }),
          _gender = this.state.data.gender && this.state.data.gender.map(_g => {
                return (<RadioButton key={_g.id} value={_g.code}>{_g.name}</RadioButton>)
            }),

          _title = this.state.data.title && this.state.data.title.map(_h => {
                return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
            }),
          { getFieldProps, getFieldError, isFieldValidating } = this.props.form;


        const specialistName = getFieldProps('name', {
            rules: [
                { required: true, message: '请输入医生姓名'},
                { validator: this.checkName.bind(this)}
            ]
        });
        const specialistHospital = getFieldProps('hospital', {
            rules: [
                { required: true, message: '请选择所属医院'}
            ]
        });
        const specialistDepartment = getFieldProps('department', {
            rules: [
                { required: true, message: '请选择所属科室'}
            ]
        });
        const specialistTitle = getFieldProps('title', {
            rules: [
                { required: true, message: '请选择职称'}
            ]
        });
        const specialistDesc = getFieldProps('brief_introduction', {
            rules: [
                { required: true, message: '请输入医生介绍'}
            ]
        });
        const specialistDomain = getFieldProps('domain', {
            rules: [
                { required: true, message: '请输入医生擅长领域'}
            ]
        });
        const specialistModalities = getFieldProps('modalities', {
            rules: [
                { required: true, type:'array', message: '请勾选医生阅片类型'}
            ]
        });
        const idCardProps = getFieldProps('idcard', {
            rules: [
                { required: true,message:'请填写身份证号' },
                { validator: this.checkIdcard.bind(this) }
            ]
        });
        const genderProps = getFieldProps('gender', {
            rules: [
                { required: true, message: '请选择专家性别' }
            ]
        });
        const dateData = [
            { label: '周一', value: 1 },
            { label: '周二', value: 2 },
            { label: '周三', value: 3 },
            { label: '周四', value: 4 },
            { label: '周五', value: 5 },
            { label: '周六', value: 6 },
            { label: '周日', value: 7 }
        ];
        const serviceColumns = [
            {
                title: '时间段',
                dataIndex: 'label',
                width: 90,
                size: 'small'
            },{
                title: '日期',
                dataIndex: 'active',
                render(text,record){
                    const _d = getFieldProps(record.id, {
                        rules: [
                            { type:'array'}
                        ]
                    });
                    return (
                      <CheckboxGroup
                        {..._d}
                        options = {dateData}
                      />
                    )
                }
            }
        ];
        const portraitProps = getFieldProps('portrait', {
            normalize: this.normFile.bind(this),
            onChange: this.portraitHandler.bind(this)
        }),files_report = getFieldProps('files', {
            normalize: this.normFile,
            onChange: this.uploadChangeHandler.bind(this,'certificate')
        }),
          fl = this.state.attachment;
        return (
          <div>
              <Alert
                type="info"
                showIcon
                closeText="知道了"
                message="您的账号已经创建成功，请提交您的资质信息，我们审核通过后将为您开放所有专家用户的权限，谢谢合作！" />
              <Form horizontal form={this.props.form}>
                  <FormItem
                    {...formItemLayout}
                    label="专家头像"
                  >
                      <Upload
                        name="files"
                        showUploadList={false}
                        action={`${API_URL}upload/portrait?accessToken=${this.state.user.accessToken}`}
                        beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                        help="只能上传图片格式的文件"
                        {...portraitProps}
                      >
                          <div style={{
                                width: '100px',
                                overflow: 'hidden',
                                backgroundColor: '#ddd',
                                textAlign: 'center'
                            }}>
                              {curPortrait?<img style={{
                                display: 'block',
                                width: '100%'
                            }} src={curPortrait.url} />:'没有上传头像'}
                          </div>
                          <Button type="ghost">
                              <Icon type="upload" /> 选择并上传头像
                          </Button>
                      </Upload>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="姓名"
                  >
                      <Input
                        {...specialistName}
                        placeholder="请输入专家姓名"
                      />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="性别"
                  >
                      <RadioGroup {...genderProps}>
                          {_gender}
                      </RadioGroup>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="职称"
                  >
                      <Select
                        {...specialistTitle}
                        showSearch
                        placeholder="请选择职称"
                        optionFilterProp="children"
                        notFoundContent="无法找到"
                      >
                          {_title}
                      </Select>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="资质证件"
                    help={`请上传资质或证件图片`}
                  >
                      <Upload
                        name='files'
                        action={`${API_URL}upload/certificate?accessToken=${this.state.user.accessToken}`}
                        defaultFileList={fl}
                        multiple={true}
                        listType="picture"
                        beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                        {...files_report}
                      >
                          <Button type="ghost" >
                              <Icon type="upload" /> 选择资质图片并上传
                          </Button>
                      </Upload>
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="身份证号"
                  >
                      <Input {...idCardProps} placeholder="请输入身份证号" />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="所属医院"
                  >
                      <Input {...specialistHospital} placeholder="请输入所属医院" />
                  </FormItem>
                  <FormItem {...formItemLayout} label="所属科室" >
                      <Select {...specialistDepartment} showSearch placeholder="请选择所属科室" optionFilterProp="children" notFoundContent="无法找到">{_departments}</Select>
                  </FormItem>
                  <FormItem {...formItemLayout.ignore} label="阅片类型">
                      <CheckboxGroup {...specialistModalities} options={_modalities} />
                  </FormItem>
                  <FormItem {...formItemLayout} label="擅长领域">
                      <Input type="textarea" {...specialistDomain} />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="简介"
                  >
                      <Input type="textarea" {...specialistDesc} />
                  </FormItem>
                  <FormItem
                    label="服务时段"
                    {...formItemLayout.ignore}
                  >
                      <Table columns={serviceColumns} dataSource={tempServiceData} pagination={false} />
                  </FormItem>
                  <FormItem wrapperCol={formItemLayout.noLabel}>
                      <Button type="primary" onClick={this.handleSubmit}>提交</Button>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      <Button
                        onClick={function(){
                        this.context.router.goBack(-1)
                       }.bind(this)}>取消</Button>
                  </FormItem>
              </Form>
          </div>
        )
    }

}
const FillInfo = createForm()(_FillInfo);
class FeedBack extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            status: this.props.user.user.ispass || 0
        }
    }
    backToEdit(){
        this.props.backToEdit()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            status:nextProp.user.user.ispass
        })
    }
    render(){
        const _step = parseInt(this.state.status),
          user = this.props.user.user,
          backToEdit = (
            <Button type="primary" onClick={this.backToEdit.bind(this)}>修改个人信息并重新提交</Button>
          ),
          _info = (
            <ul className="label-list">
                <li><label>用户名</label>{user.username}</li>
                <li><label>姓名</label>{user.name}</li>
                <li><label>性别</label>{user.gender=='M'?'男':(user.gender=='F'?'女':'未知')}</li>
                <li><label>职称</label>{user.title}</li>
                <li><label>科室</label>{user.department}</li>
                <li><label>医院</label>{user.hospital}</li>
                <li><label>简介</label>{user.brief_introduction}</li>
                <li><label>擅长领域</label>{user.domain}</li>
            </ul>
          );
        switch (_step){
            case 0:
            return (
              <div>
                  <Alert message="专家注册申请提交成功"
                     description={`恭喜您！专家 ${user.name}，我们已经接收到您的申请资料，将在3-5个工作日内完成您的资料审核工作，审核完成后将通知您审核结果，您也可以登录网站查询`}
                     type="info"
                     showIcon
                  />
                  {_info}
              </div>
            );
            case 2:
              const _d = (
                <div>
                  <div style={{
                    fontSize: '16px',
                    padding: '20px 0'
                  }}>{user.remarks}</div>
                </div>
              );
                return (
                  <div>
                      <Alert message="抱歉，您的申请被驳回，原因如下："
                         description={_d}
                         type="warning"
                         showIcon
                      />
                      {backToEdit}
                      {_info}
                  </div>
                );
            default:
            return (<div>未知状态</div>)
        }
    }
}
export {CheckMobBySms,SubmitCode,FillInfo,FeedBack}